package gui.user;

import database.TableDatabaseUsage;
import info.Flight;
import info.Order;
import info.Passenger;
import messages.flight.DeFLliInfoResponseMessage;
import messages.flight.DeFliInfoRequestMessage;
import messages.ticket.QRequestMessage;
import messages.ticket.QResponeMessage;
import messages.user.UPInfoRequestMessage;
import messages.user.UPInfoResponseMessage;
import server.MessageServer;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

public class PassengerManageForm extends JFrame {
    private JTextField passengerStartTextField;
    private JTextField passengerDestinationTextField;
    private JTextField passengerNameTextField;
    private JComboBox<String> passengerFclassComboBox;
    private JTextField passengerIdTextField;
    private JTextField passengerFlightTextField;
    private JTextField passengerPriceField;

    private JTextField orderDateField;

    private JTable jt;
    private String stateType;
    private String Price = "--";

    private PMFModel pmfModel = new PMFModel();

    public PassengerManageForm(Passenger passenger) {
        super("飞机订票系统—用户主界面");

        GridBagLayout gbl = new GridBagLayout();
        GridBagConstraints gbc = new GridBagConstraints();
        setLayout(gbl);
        setPreferredSize(new Dimension(1000, 400));


        //左边界面
        JPanel leftPanel = new JPanel(new GridLayout(4,1));
        JButton queryInfoButton = new JButton("查询航班信息");
        queryInfoButton.addActionListener(e -> {
            new QueryFlightsForm();
        });

        JButton BookTicketButton = new JButton("预定机票");
        BookTicketButton.addActionListener(e -> {
            new BookTicketForm(passenger);
        });

        JButton queryOrdersButton = new JButton("订单管理");
        queryOrdersButton.addActionListener(e -> {
            System.out.println(passenger.getIdno());
            new OrderDetailsForm(passenger.getIdno());
        });

        JButton updateInfoButton = new JButton("个人信息");
        updateInfoButton.addActionListener(e -> {
            new PassengerInfoForm(passenger);
        });
        leftPanel.add(queryInfoButton);
        leftPanel.add(BookTicketButton);
        leftPanel.add(queryOrdersButton);
        leftPanel.add(updateInfoButton);


        //中间界面
        GridBagLayout midGbl = new GridBagLayout();
        GridBagConstraints midGbc = new GridBagConstraints();
        JPanel midPanel = new JPanel(midGbl);

        String[] cityNameArr = {"全部","广州","深圳","佛山"};
        JComboBox<String> cityComboBox = new JComboBox<>(cityNameArr);
        cityComboBox.addActionListener(e -> {
            String address = String.valueOf(cityComboBox.getSelectedItem());
            pmfModel.flightList = TableDatabaseUsage.getInstance().getFlightListByAddress(address);
            jt.updateUI();
        });
        JPanel spacePanel = new JPanel();

        String name = "用户"+passenger.getTelephone().substring(0,4);

        JMenu jMenu = new JMenu(name);
        JMenuBar br1 = new JMenuBar();
        JMenuItem jm1 = new JMenuItem("退出登录");
        jm1.addActionListener(e -> {
            this.dispose();
        });
        br1.setBackground(Color.cyan);
        jMenu.add(jm1);
        br1.add(jMenu);



        jt = new JTable(pmfModel);
        DefaultTableCellRenderer dc = new DefaultTableCellRenderer();
        dc.setHorizontalAlignment(JLabel.CENTER);
        jt.setDefaultRenderer(Object.class,dc);
        JTableHeader dataHeader = jt.getTableHeader();
        dataHeader.setPreferredSize(new Dimension(dataHeader.getWidth(), 30));
        dataHeader.setReorderingAllowed(false);
        jt.setRowHeight(30);
        JScrollPane sp = new JScrollPane(jt);

        midGbc.fill = GridBagConstraints.BOTH;

        midGbc.weightx = 0;
        midGbc.weighty = 0;
        midGbl.setConstraints(cityComboBox,midGbc);

        midGbc.weightx = 1;
        midGbc.weighty = 0;
        midGbl.setConstraints(spacePanel,midGbc);



        midGbc.gridwidth=GridBagConstraints.REMAINDER;
        midGbc.weightx = 0;
        midGbc.weighty = 0;
        midGbl.setConstraints(br1,midGbc);

        midGbc.weightx = 1;
        midGbc.weighty = 1;
        midGbl.setConstraints(sp,midGbc);

        midPanel.add(cityComboBox);
        midPanel.add(spacePanel);
        midPanel.add(br1);
        midPanel.add(sp);


        gbc.fill=GridBagConstraints.BOTH;
        gbc.weightx = 0;
        gbc.weighty = 0;
        gbl.setConstraints(leftPanel,gbc);

        gbc.weightx = 1;
        gbc.weighty = 1;
        gbl.setConstraints(midPanel,gbc);

        add(leftPanel);
        add(midPanel);

        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setVisible(true);
    }


    //查询乘客信息界面
    class QueryFlightsForm extends JFrame {
        public QueryFlightsForm() {
            super("查询航班信息");
            setSize(500, 300);
            setLayout(new GridLayout(3, 2));


            passengerStartTextField = new JTextField(20);
            passengerDestinationTextField = new JTextField(20);
            JButton queryInfoButton = new JButton("点击查询航班信息");
            queryInfoButton.addActionListener(e -> {
                new FlightTicketForm(passengerStartTextField.getText(),
                        passengerDestinationTextField.getText());
            });
            JLabel l1 = new JLabel("起点：");
            JLabel l2 = new JLabel("终点：");

            l1.setHorizontalAlignment(JLabel.CENTER);
            l2.setHorizontalAlignment(JLabel.CENTER);
            add(l1);
            add(passengerStartTextField);
            add(l2);
            add(passengerDestinationTextField);
            add(new JLabel(""));
            add(queryInfoButton);
            setLocationRelativeTo(null);

            setVisible(true);
        }
    }

    class BookTicketForm extends JFrame {
        public BookTicketForm(Passenger passenger){
            super("预定机票");
            setSize(600, 400);
            setLayout(new GridLayout(7, 2));

            String[] fclassTypes = {"选择舱位","经济舱", "头等舱", "商务舱"};

            passengerNameTextField = new JTextField();
            passengerNameTextField.setText(passenger.getpName());
            passengerNameTextField.setEditable(false);

            passengerIdTextField = new JTextField();
            passengerIdTextField.setText(passenger.getIdno());
            passengerIdTextField.setEditable(false);

            passengerFlightTextField = new JTextField(20);
            passengerFlightTextField.setToolTipText("请输入航班号");


            passengerFclassComboBox = new JComboBox<>(fclassTypes);
            passengerFclassComboBox.setSelectedIndex(0);

            passengerFclassComboBox.addActionListener(e -> {
                if(passengerFclassComboBox.getSelectedIndex() == 1){
                    stateType ="经济舱";
                    if(passengerFlightTextField.getText()!="请输入航班号"&&passengerFlightTextField.getText()!="") {
                        Price= String.valueOf(sendQueryInfor(passengerFlightTextField.getText(), stateType));
                    }else {
                        JOptionPane.showMessageDialog(null,"请输入正确的航班号!");
                    }
                    passengerPriceField.setText(Price);

                }

                if(passengerFclassComboBox.getSelectedIndex() == 2){
                    stateType ="头等舱";
                    if(passengerFlightTextField.getText()!="请输入航班号"&&passengerFlightTextField.getText()!="") {
                        Price = String.valueOf(sendQueryInfor(passengerFlightTextField.getText(), stateType));
                    }else {
                        JOptionPane.showMessageDialog(null,"请输入正确的航班号!");
                    }
                    passengerPriceField.setText(Price);
                }

                if(passengerFclassComboBox.getSelectedIndex() == 3){
                    stateType ="商务舱";
                    if(passengerFlightTextField.getText()!="请输入航班号"&&passengerFlightTextField.getText()!="") {
                        Price = String.valueOf(sendQueryInfor(passengerFlightTextField.getText(), stateType));
                    }else {
                        JOptionPane.showMessageDialog(null,"请输入正确的航班号!");
                    }
                    passengerPriceField.setText(Price);
                }
            });



            passengerPriceField = new JTextField(20);
            passengerPriceField.setText(Price);
            passengerPriceField.setEditable(false);

            orderDateField = new JTextField();
            orderDateField.setToolTipText("请输入订票日期：“2001-01-01”");



            JButton BookTicketButton = new JButton("预定机票");
            BookTicketButton.addActionListener(e -> {
                int selectedIndex = JOptionPane.showOptionDialog(null,"是否付款","付款确认",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,   null,
                        new String[]{"确定","取消"},"确定");
                switch (selectedIndex){
                    case 0:
                        Order order = addOrder(0,passenger);
                        JOptionPane.showMessageDialog(this,"支付成功！");
                        new OrderDetails(order);
                        break;
                    case 1:
                        addOrder(1,passenger);
                        JOptionPane.showMessageDialog(this,"您还未付款，请到订单页面付款");
                        break;
                    default:
                        JOptionPane.showMessageDialog(this,"error");
                        this.dispose();
                        break;
                }
                this.dispose();

            });
            JLabel l1 = new JLabel("姓名:");
            JLabel l2 = new JLabel("身份证:");
            JLabel l3 = new JLabel("航班号:");
            JLabel l4 = new JLabel("舱位:");
            JLabel l5 = new JLabel("价格:");
            JLabel l6 = new JLabel("日期:");

            l1.setHorizontalAlignment(JLabel.CENTER);
            l2.setHorizontalAlignment(JLabel.CENTER);
            l3.setHorizontalAlignment(JLabel.CENTER);
            l4.setHorizontalAlignment(JLabel.CENTER);
            l5.setHorizontalAlignment(JLabel.CENTER);
            l6.setHorizontalAlignment(JLabel.CENTER);

            add(l1);
            add(passengerNameTextField);
            add(l2);
            add(passengerIdTextField);
            add(l3);
            add(passengerFlightTextField);
            add(l4);
            add(passengerFclassComboBox);
            add(l5);
            add(passengerPriceField);
            add(l6);
            add(orderDateField);


            add(new JLabel());
            add(BookTicketButton);

            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setLocationRelativeTo(null);
            setVisible(true);
        }

        private Order addOrder(int statusNum,Passenger passenger){
            Order order = new Order();

            Date utilDate;
            java.sql.Date sqlDate;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                utilDate = sdf.parse(orderDateField.getText());

            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            sqlDate = new java.sql.Date(utilDate.getTime());

            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedNow = now.format(formatter);

            order.setIDNO(passenger.getIdno());
            order.setFlight(passengerFlightTextField.getText());
            order.setFdate(sqlDate);
            order.setFclass((String) passengerFclassComboBox.getSelectedItem());

            if(statusNum == 0){
                order.setOrderState("已付款");
            }else if (statusNum == 1){
                order.setOrderState("未付款");
            }

            order.setOrderTime(formattedNow);

            TableDatabaseUsage.getInstance().insertToOrder(order);
            ODFModel.orderList = TableDatabaseUsage.getInstance().getOrderList();
            if(OrderDetailsForm.ordersTable != null){
                OrderDetailsForm.ordersTable.updateUI();
            }

            return order;
        }

    }

    private double sendQueryInfor(String flightid, String stateType) {
        QRequestMessage qRequestMessage = new QRequestMessage();
        QResponeMessage qResponeMessage;
        qRequestMessage.setFlightid(flightid);
        qRequestMessage.setStateType(stateType);
        try {
            MessageServer.getInstance().getOos().writeObject(qRequestMessage);
            System.out.println("客户端发送请求成功！"+qRequestMessage);
            qResponeMessage = (QResponeMessage) MessageServer.getInstance().
                    getOis().readObject();
            System.out.println("客户端收到服务端的响应成功！"+qResponeMessage);
            return qResponeMessage.getIsPrice();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }


    private JTextField nameInfoTextField;
    private JTextField identityNumInfoTextField;
    private JTextField phoneInfoTextField;
    private Passenger cachePassenger = new Passenger();
    class PassengerInfoForm extends JFrame {
        public PassengerInfoForm(Passenger passenger) {
            super("个人信息");
            setSize(500, 500);
            setLayout(new GridLayout(4, 2));

            cachePassenger = passenger;

            nameInfoTextField = new JTextField(cachePassenger.getpName());
            nameInfoTextField.setEditable(false);

            identityNumInfoTextField = new JTextField(cachePassenger.getIdno());
            identityNumInfoTextField.setEditable(false);

            phoneInfoTextField = new JTextField(cachePassenger.getTelephone());
            phoneInfoTextField.setEditable(false);

            JButton updateInfoButton = new JButton("修改信息");
            updateInfoButton.addActionListener(e -> {
                new UpdatePassengerInfoForm(cachePassenger);
            });

            JLabel l1 = new JLabel("姓名：");
            JLabel l2 = new JLabel("身份证：");
            JLabel l3 = new JLabel("电话：");

            // 设置居中
            l1.setHorizontalAlignment(JLabel.CENTER);
            l2.setHorizontalAlignment(JLabel.CENTER);
            l3.setHorizontalAlignment(JLabel.CENTER);

            add(l1);
            add(nameInfoTextField);
            add(l2);
            add(identityNumInfoTextField);
            add(l3);
            add(phoneInfoTextField);
            add(new JLabel(""));
            add(updateInfoButton);

            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setVisible(true);
        }
    }

    class UpdatePassengerInfoForm extends JFrame {
        JTextField nameTextField;
        JTextField identityNumTextField;
        JTextField phoneTextField;
        private String oldIDNum;
        private Passenger newPassenger = new Passenger();

        public UpdatePassengerInfoForm(Passenger passenger) {
            super("修改个人信息");
            setSize(500, 500);
            setLayout(new GridLayout(4, 2));
            oldIDNum = passenger.getIdno();
            nameTextField = new JTextField(passenger.getpName());
            identityNumTextField = new JTextField(passenger.getIdno());
            phoneTextField = new JTextField(passenger.getTelephone());
            JButton updateInfoButton = new JButton("提交修改");
            updateInfoButton.addActionListener(e -> {
                newPassenger.setIdno(identityNumInfoTextField.getText());
                newPassenger.setpName(nameTextField.getText());
                newPassenger.setTelephone(phoneTextField.getText());
                sendUpdatePassengerInfoMsg(newPassenger,oldIDNum);
                dispose();
            });

            JLabel l1 = new JLabel("姓名：");
            JLabel l2 = new JLabel("证件号：");
            JLabel l3 = new JLabel("电话：");

            // 设置居中
            l1.setHorizontalAlignment(JLabel.CENTER);
            l2.setHorizontalAlignment(JLabel.CENTER);
            l3.setHorizontalAlignment(JLabel.CENTER);

            add(l1);
            add(nameTextField);
            add(l2);
            add(identityNumTextField);
            add(l3);
            add(phoneTextField);

            add(new JLabel(""));
            add(updateInfoButton);

            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setVisible(true);


        }

        private boolean sendUpdatePassengerInfoMsg(Passenger passenger,String oldIDNum){
            UPInfoRequestMessage up_req_msg = new UPInfoRequestMessage();
            UPInfoResponseMessage up_ack_msg;
            up_req_msg.setPassenger(passenger);
            up_req_msg.setOldIDNum(oldIDNum);

            try {
                MessageServer.getInstance().getOos().writeObject(up_req_msg);
                System.out.println("客户端发送请求成功！"+up_req_msg);
                up_ack_msg = (UPInfoResponseMessage) MessageServer.getInstance().
                        getOis().readObject();
                System.out.println("客户端收到服务端的响应成功！"+up_ack_msg);
            } catch (IOException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }

            updateInfo(up_ack_msg.getNewPassenger());
            return true;
        }

        private void updateInfo(Passenger newPassenger){
            cachePassenger.setpName(newPassenger.getpName());
            cachePassenger.setIdno(newPassenger.getIdno());
            cachePassenger.setTelephone(newPassenger.getTelephone());
            nameInfoTextField.setText(newPassenger.getpName());
            identityNumInfoTextField.setText(newPassenger.getIdno());
            phoneInfoTextField.setText(newPassenger.getTelephone());
        }
    }

    class OrderDetails extends JFrame{

        private JTextField orderNoField;
        private JTextField idNoField;
        private JTextField flightField;

        private JTextField fdateField;
        private JTextField fclassField;
        private JTextField discountField;
        private JTextField orderStateField;
        private JTextField orderTimeField;

        public OrderDetails(Order order){
            super("订单详情");
            setSize(500,500);
            setLayout(new GridLayout(8,2));


            JLabel j1 = new JLabel("订单号：");
            JLabel j2 = new JLabel("身份证号：");
            JLabel j3 = new JLabel("航班号：");
            JLabel j4 = new JLabel("航班日期：");
            JLabel j5 = new JLabel("舱位：");
            JLabel j6 = new JLabel("折扣：");
            JLabel j7 = new JLabel("订单状态：");
            JLabel j8 = new JLabel("订票时间：");

            j1.setHorizontalAlignment(SwingConstants.CENTER);
            j2.setHorizontalAlignment(SwingConstants.CENTER);
            j3.setHorizontalAlignment(SwingConstants.CENTER);
            j4.setHorizontalAlignment(SwingConstants.CENTER);
            j5.setHorizontalAlignment(SwingConstants.CENTER);
            j6.setHorizontalAlignment(SwingConstants.CENTER);
            j7.setHorizontalAlignment(SwingConstants.CENTER);
            j8.setHorizontalAlignment(SwingConstants.CENTER);

            orderNoField = new JTextField(order.getOrderNo());
            orderNoField.setEditable(false);
            idNoField = new JTextField(order.getIDNO());
            idNoField.setEditable(false);
            flightField = new JTextField(order.getFlight());
            flightField.setEditable(false);
            fdateField = new JTextField(String.valueOf(order.getFdate()));
            fdateField.setEditable(false);
            fclassField = new JTextField(String.valueOf(order.getClass()));
            fclassField.setEditable(false);
            discountField = new JTextField(String.valueOf(order.getDiscount()));
            discountField.setEditable(false);
            orderStateField = new JTextField(order.getOrderState());
            orderStateField.setEditable(false);
            orderTimeField = new JTextField(order.getOrderTime());
            orderTimeField.setEditable(false);

            add(j1);
            add(orderNoField);
            add(j2);
            add(idNoField);
            add(j3);
            add(flightField);
            add(j4);
            add(fdateField);
            add(j5);
            add(fclassField);
            add(j6);
            add(discountField);
            add(j7);
            add(orderStateField);
            add(j8);
            add(orderTimeField);



            this.setLocationRelativeTo(null);
            this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            this.setVisible(true);
        }
    }



    class PMFModel extends AbstractTableModel{
        private String[] columnNames = {"航班号","起飞站", "起飞时间", "到达站", "到达时间", "登机时间", "登机口"};
        public List<Flight> flightList = TableDatabaseUsage.getInstance().getFlightList();


        @Override
        public int getRowCount() {
            return flightList.size();
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Flight dataInfo = flightList.get(rowIndex);
            if(columnIndex == 0) {
                return dataInfo.getFlight();
            } else if(columnIndex == 1) {
                return dataInfo.getDEPA();
            } else if(columnIndex == 2) {
                return dataInfo.getDEPATime();
            } else if(columnIndex == 3) {
                return dataInfo.getDEST();
            } else if(columnIndex == 4) {
                return dataInfo.getDESTTIME();
            }else if(columnIndex == 5){
                return dataInfo.getBoarding();
            }else if(columnIndex == 6){
                return dataInfo.getGate();
            }
            return null;
        }
    }
}

